<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

// 首页设置  middleware(['web'])->
//Route::get('/', function() { return view('welcome'); });
//Route::get('/', 'App\Http\Controllers\Frontend\HomeController@index');


// 数据库
Route::match(
    ['post', 'get',],
    '/db/{action?}',
    function($action = 'index') {
        try{
            // 执行请求
            $file   = 'App\Http\Controllers\Test\DatabaseController';
            $file   = App::make($file);
            $result = $file->$action();

            return $result;
        } catch(Exception $e){
            return ['code' => 1, 'msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()];
        }
    }
)->where(['action' => '[0-9a-zA-Z-]+'])->name('db'); // 统一命令


// 前台页面
Route::match(
    ['get', 'post'],
    '/{controller?}/{action?}/{param1?}/{param2?}/{param3?}', // .html
    function($controller = '', $action = '', $param1 = '', $param2 = '', $param3 = '') {

        $request = request();
        $post    = [];
        //$post    = $request->all();

        try{
            // 各种情况下的参数组合
            // 与 $controller 和 $action 有关
            if($param1){
                $param1 = str_replace('.html', '', $param1);
            }
            if($param2){
                $param2 = str_replace('.html', '', $param2);
            }
            if($param3){
                $param3 = str_replace('.html', '', $param3);
            }
            if($action){
                $action = str_replace('.html', '', $action);
            }

            // 这里是英文网站的特例
            if($controller){
                $controllerStr = str_replace('.html', '', $controller);
                $isAjax        = $request->ajax();
                $controllers   = explode('-', $controllerStr);
                // 组合控制器与操作
                $controller    = strtolower($controllers[0]);
                $controllerNum = count($controllers) - 1;
                if($controller == 'home'){
                    $action       = $isAjax ? 'more' : 'index';
                    $controller   = 'article';
                    $post['page'] = $controllers[$controllerNum] ?? 1;
                } elseif($controller == 'rss'){
                    $action       = $isAjax ? 'more' : 'index';
                    $controller   = 'rss';
                    $post['page'] = $controllers[$controllerNum] ?? 1;
                } elseif($controller == 'push'){
                    $action     = $isAjax ? 'more' : 'index';
                    $controller = 'push';

                    // 一些指定操作
                    if(!empty($controllers[1])){
                        if($controllers[1] == 'toemail'){
                            $action = 'toEmail';
                        } elseif($controllers[1] == 'cancelemail'){
                            $action = 'cancelEmail';
                        }
                    }

                    if(is_numeric($controllers[$controllerNum])){
                        $post['page'] = $controllers[$controllerNum];
                    }
                } elseif($controller == 'cate'){
                    $action        = $isAjax ? 'more' : 'index';
                    $post['title'] = substr($controllerStr, 5);
                    if(is_numeric($controllers[$controllerNum]) &&($controllers[$controllerNum] < 1000)){
                        $post['page']  = $controllers[$controllerNum];
                        $post['title'] = substr($controllerStr, 5, -strlen($controllers[$controllerNum]) - 1);
                    }
                } elseif($controller == 'tags'){
                    $action        = $isAjax ? 'more' : 'index';
                    $post['title'] = substr($controllerStr, 5);
                    if(is_numeric($controllers[$controllerNum])){
                        $post['page']  = $controllers[$controllerNum];
                        $post['title'] = substr($controllerStr, 5, -strlen($controllers[$controllerNum]) - 1);
                    }
                } elseif($controller == 'search'){
                    //$post['keyword'] = substr($controllerStr, 7);
                    $action = $action ?: ($isAjax ? 'more' : 'index');
                } elseif($controller == 'email'){
                    $action = substr($controllerStr, 6);
                    $action = $action ?: 'index';
                    if(count($controllers) == 3){
                        $post['page'] = $controllers[$controllerNum];
                        $action       = $controllers[1];
                    }


                } elseif($controller == 'article'){
                    $action     = 'index';
                    $post['id'] = $controllers[$controllerNum];
                } elseif($controller == 'site'){
                    $action = $controllers[1] ?? 'index';
                } else{
                    // 查询
                    $controllers = explode('/', $controllerStr);
                    $controllers = array_filter($controllers);
                    if(count($controllers) > 1){
                        $controller   = $controllers[0];
                        $action       = $controllers[1];
                        $post['link'] = $controllerStr;
                    } elseif($controllerStr == 'emaillist'){
                        $controller = 'email';
                        $action     = 'lists';
                    } else{
                        $controller   = 'article';
                        $action       = 'index';
                        $post['link'] = $controllerStr;
                    }
                }
            }

            // 首页
            if(empty($controller) && empty($action)){
                // 重新定义控制器与方法
                $controller = 'home';
                $action     = 'index';
            }
            if($controller == 'home'){
                if($action == 'down-word'){
                    $post['date'] = $param1;
                }
            }
            // 参数
            $post['controller'] = $controller;
            $post['action']     = $action;


            // 控制器   中划线 => 驼峰式:大小写
            $controller = str_replace(' ', '', ucwords(str_replace('-', ' ', $controller)));
            $file       = 'App\Http\Controllers\Frontend\\'.$controller.'Controller';
            $action     = str_replace(' ', '', ucwords(str_replace('-', ' ', $action)));
            $action     = lcfirst($action);
            // 判断文件是是否存在
            /*$path = '../'.$file.'.php';
            $path = str_replace('App', 'app', $path);
            if(!is_file($path)){
                // echo $file.'类不存在！！';
                throw new \RuntimeException($file.'类文件不存在！！', 400);
            }*/

            if(class_exists($file)){
                // 获取请求参数
                $request->merge($post);
                // 执行请求
                $file   = App::make($file);
                $result = $file->$action();

                // 首页：保存为静态文件
                //   当请求过大的时候，Nginx限制访问，默认访问该静态页面
                if(($controller == 'Home') && ($action == 'index')){
                    $filePath = public_path('homepage.html');
                    $is_make  = true; // 默认不重新生成首页
                    if(file_exists($filePath)){
                        $is_make = LARAVEL_TIME - filemtime($filePath) > 86400 ? true : false;
                    }
                    if($is_make){
                        file_put_contents($filePath, $result);
                    }
                }

                if($result instanceof \Illuminate\View\View){
                    // 可以在这里对视图进行一些检查或者处理
                    //var_dump($result->getData());
                    //die;
                }
                // 展示错误  不成功
                /*if($result instanceof \ErrorException){
                    var_dump($result->getData());
                    die;
                }*/

                return $result;
            } else{
                //die($file.'类不存在！！');
                throw new Exception($file.'类不存在！！');
            }
        } catch(Exception $e){
            $result = ['code' => $e->getCode(), 'msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()];

            if($request->ip() == '127.0.0.1'){
                return $result;
            } else{
                return view('404', $result);
            }
        }
    }
//)->where(['controller' => '[0-9a-zA-Z-\.]+', 'action' => '[0-9a-zA-Z-\.]+'])->name('frontend'); // 统一命令
)->where(['controller' => '.*', 'action' => '.*'])->name('frontend'); // 统一命令


// 判断是否是手机端
function isMobile():bool
{
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if(isset ($_SERVER['HTTP_X_WAP_PROFILE'])){
        return true;
    }

    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if(isset ($_SERVER['HTTP_VIA'])){
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;// 找不到为flase,否则为TRUE
    }

    // 判断手机发送的客户端标志,兼容性有待提高
    if(isset ($_SERVER['HTTP_USER_AGENT'])){
        $clientkeywords = array(
            'mobile',
            'nokia',
            'sony',
            'ericsson',
            'mot',
            'samsung',
            'htc',
            'sgh',
            'lg',
            'sharp',
            'sie-',
            'philips',
            'panasonic',
            'alcatel',
            'lenovo',
            'iphone',
            'ipod',
            'blackberry',
            'meizu',
            'android',
            'netfront',
            'symbian',
            'ucweb',
            'windowsce',
            'palm',
            'operamini',
            'operamobi',
            'openwave',
            'nexusone',
            'cldc',
            'midp',
            'wap',
        );
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if(preg_match("/(".implode('|', $clientkeywords).")/i", strtolower($_SERVER['HTTP_USER_AGENT']))){
            return true;
        }
    }

    if(isset ($_SERVER['HTTP_ACCEPT'])){ // 协议法，因为有可能不准确，放到最后判断
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))){
            return true;
        }
    }

    return false;
}
